package com.note.user.config;

import com.note.common.constants.RabbitConst;
import jakarta.annotation.Resource;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

/**
 * @Package：com.mom.o.config
 * @Name：DirectRabbitConfig
 * @Author：热伊木
 * @Email：uyevan@163.com
 * @Date：2024-04-12-14:11
 * @Description：RabbitTopic初始化创建配置类 --- 运行应用时就会创建Topic
 */

@Component
public class DirectRabbitConfig implements BeanPostProcessor/*用于管理 Bean 生命周期*/ {

    @Resource
    private RabbitAdmin rabbitAdmin;

    public Queue rabbitmqDemoDirectQueue() {
        /*
         * 1、name:    队列名称
         * 2、durable: 是否持久化
         * 3、exclusive: 是否独享、排外的。如果设置为true，定义为排他队列。则只有创建者可以使用此队列。也就是private私有的。
         * 4、autoDelete: 是否自动删除。也就是临时队列。当最后一个消费者断开连接后，会自动删除。
         */
        return new Queue(RabbitConst.RabbitMQTopic, true, false, false);
    }

    public DirectExchange rabbitmqDemoDirectExchange() {
        //Direct交换机
        return new DirectExchange(RabbitConst.RabbitMQDirectExchange, true, false);
    }

    //初始化RabbitAdmin对象
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        RabbitAdmin ra = new RabbitAdmin(connectionFactory);
        ra.setAutoStartup(true);
        return ra;
    }

    //RabbitAdmin对象后置操作(创建对象后执行)
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //创建交换机
        rabbitAdmin.declareExchange(rabbitmqDemoDirectExchange());
        //创建队列
        rabbitAdmin.declareQueue(rabbitmqDemoDirectQueue());
        return null;
    }

    @Bean
    public Binding bindDirect() {
        //链式写法，绑定交换机和队列，并设置匹配键
        return BindingBuilder
                //绑定队列
                .bind(rabbitmqDemoDirectQueue())
                //到交换机
                .to(rabbitmqDemoDirectExchange())
                //并设置匹配键
                .with(RabbitConst.RabbitMQDirectRouting);
    }

}


